import { storeBindingsBehavior } from "mobx-miniprogram-bindings";
import router from "@src/router";
import base from "@src/store/base";
import location from "@src/store/location";
import {
  getAppointmentPlanList,
  getAppointmentResourcesList,
  getAppointmentShopDetail,
  queryNearbyShopList,
} from "@src/api/reservation";
import {
  PROJECT_TYPE,
  PROJECT_STATE,
  RESOURCES_STATE,
  OPEN_STATE,
  RESOURCES_TYPE,
  OPEN_STATE_CLEW_TEXT,
} from "@src/sp-reservation/constant/index.js";
import { debounce, throttle } from "@src/common/utils.js";

Page({
  behaviors: [storeBindingsBehavior, router.routerBehavior],
  storeBindings: [
    {
      store: base,
      fields: ["themeColor", "themeTitleColor", "perms", "businessName"],
    },
    {
      store: location,
      fields: ["latitude", "longitude"],
      actions: ["getLocation", "showAuthTip"],
    },
  ],
  observers: {
    // scrollTop: function () {
    //   console.log("scrollTop", val);
    // },
  },
  data: {
    OPEN_STATE,
    //nav start
    navHeight: 44,
    loading: false,
    canScrollY: false,
    isShowShopInfo: true,
    //nav end
    //滑动 start
    originShopScroll: 0, //原始高度
    isScrollToTop: false,
    mustFixOffset: 200,
    //滑动 end
    shopId: "",
    shopConfigId: "",
    shopDetail: {},
    isShopOff: false,
    PROJECT_STATE,
    RESOURCES_STATE,
    tabsActived: PROJECT_TYPE,
    tabsOptions: [PROJECT_STATE, RESOURCES_STATE],
    OPEN_STATE_CLEW_TEXT,
    list: [],
    shopList: [],
    params: {
      pageSize: 10,
      pageNum: 1,
      name: "",
    },
    isLoading: true,
    //----搜索框start---
    isInputFocus: false,
    //----搜索框end---
    //列表吸顶
    topHeight: 0,
    hasNextPage: true,
    listHeight: "",
    homeHeight: "",
  },
  onLoad: function (options) {
    // document.body.addEventListener('touchmove', function(e){
    //   if (e._isScroller) return;
    //   // 阻止默认事件
    //   e.preventDefault();
    // }, {
    //   passive: false
    // })

    wx.showLoading({ title: "加载中" });
    let shopId = null;
    if (options.GLOBAL_SHOP_ID) {
      shopId = options.GLOBAL_SHOP_ID;
    }
    if (options.shopId) {
      shopId = options.shopId;
    }
    this.setData({ shopId: shopId });
  },
  // 监听页面
  onPageScroll() {
    // this.onTouchFixed();
  },
  onShareAppMessage() {},
  onShareTimeline() {},
  //下拉刷新
  onPullDownRefresh() {
    const { latitude, longitude } = this.data;
    this.setData({
      isScrollToTop: false,
    });
    wx.showLoading({ title: "加载中" });
    this.getNearbyShop(latitude, longitude);
    this.setData({ loading: true });
    this.resetPage();
    this.fetchData(true);
  },
  handleCloseShopOff() {
    this.setData({
      isShopOff: false,
    });
  },
  onLogin() {
    this.getLocation(true)
      .then((res) => {
        this.setData({ latitude: res.latitude, longitude: res.longitude });
        if (this.data.shopId) {
          this.fetchData(true);
        } else {
          this.getNearbyShop(res.latitude, res.longitude);
        }
      })
      .catch((res) => {
        if (this.data.shopId) {
          this.fetchData(true);
        } else {
          this.getNearbyShop();
        }
      });
  },
  getNearbyShop(latitude, longitude) {
    let data = {};
    if (latitude) {
      data["latitude"] = latitude;
      data["longitude"] = longitude;
    }

    queryNearbyShopList(data).then((res) => {
      if (res.code === 0) {
        const shopList = res.data.filter((v) => v.allStatus === OPEN_STATE.ON);
        console.log("附近门店", shopList);
        if (!this.data.shopId) {
          // this.setData({  shopList });
          this.setData({
            shopId: shopList[0]?.shopId || res.data[0].shopId,
            shopList,
          });
        }
        wx.nextTick(() => {
          this.fetchData(true);
        });
      }
    });
  },
  resetPage() {
    this.setData({
      params: {
        ...this.data.params,
        pageSize: 10,
        pageNum: 1,
      },
      isInputFocus: false,
    });
  },
  //获得门店信息等
  changeShop(info) {
    this.resetPage();
    wx.showLoading({ title: "加载中" });
    const {
      detail: {
        shopId: { shopId, shopConfigId },
      },
    } = info;
    console.log("获得门店信息等", info);
    this.setData({
      list: [],
      shopId,
      shopConfigId,
    });
    this.fetchData(true);
  },
  async fetchData(isClear) {
    this.setData({
      isLoading: true,
    });
    const { shopId, latitude, longitude } = this.data;
    let newShopId = shopId;
    if (!shopId) {
      newShopId =
        this.data.shopList.filter((v) => v.allStatus === OPEN_STATE.ON)[0]
          .shopId || "";
    }
    console.log("门店id", newShopId, latitude, "---", longitude);
    const { code, data } = await getAppointmentShopDetail({
      shopId: newShopId,
      latitude: latitude || "",
      longitude: longitude || "",
    });
    //获取门店信息
    if (code === 0) {
      wx.hideLoading();
      wx.stopPullDownRefresh();
      const shopTags = [];
      const tags = data.shopLabel.split(",");
      tags.map((v) => {
        if (v.trim()) {
          shopTags.push(v);
        }
      });
      data.shopTags = shopTags;
      data.shopInfoResp.distance = (data.shopInfoResp.distance / 1000).toFixed(
        2
      );
      this.setData({
        shopDetail: { ...data, ...data.shopInfoResp },
        loading: false,
        shopConfigId: data.shopInfoResp.shopConfigId,
      });
      //打烊
      this.setData({
        isShopOff:
          this.data.shopDetail.shopInfoResp.allStatus === OPEN_STATE.CLOSE,
      });
      if (
        !(
          this.data.shopDetail.shopInfoResp.allStatus === OPEN_STATE.ON ||
          this.data.shopDetail.shopInfoResp.allStatus === OPEN_STATE.REST
        )
      ) {
        wx.showToast({
          title:
            OPEN_STATE_CLEW_TEXT[this.data.shopDetail.shopInfoResp.allStatus],
          icon: "none",
          duration: 3000,
        });
      }
      await this.getList(isClear);
    }
    // this.setData({ loading: false });
  },
  async getList(isClear = false) {
    if (isClear) {
      this.resetPage();
    }
    const { shopId, params, tabsActived } = this.data;
    params.shopId = shopId;
    const api =
      tabsActived === PROJECT_TYPE
        ? getAppointmentPlanList
        : getAppointmentResourcesList;
    let {
      code: listCode,
      data: { list: listData, hasNextPage },
    } = await api(params).catch((err) => {
      const {
        data: { code },
      } = err;
      if (code === -1) {
        if (isClear) {
          this.setData({
            list: [],
          });
        }
      }
    });
    if (listCode === 0) {
      if (!Array.isArray(listData)) {
        listData = [];
      }
      wx.stopPullDownRefresh();
      // //请求数据成功后
      if (tabsActived === RESOURCES_TYPE) {
        listData.map((v) => {
          let labels = [];
          const label = v.label.split(";");
          if (label.length > 0) {
            label.map((v) => {
              if (v) {
                labels.push(v);
              }
            });
          }
          v.labels = JSON.parse(JSON.stringify(labels));
          if (labels.length > 3) {
            v.label = labels.splice(0, 3);
          } else {
            v.label = labels;
          }
        });
      }
      this.setData({
        hasNextPage,
        list: isClear ? listData : [...this.data.list, ...listData],
        isLoading: false,
      });
    }
    // this.setData({ loading: false });
  },

  onClickChangeActivedTab(e) {
    wx.showLoading({ title: "加载中" });
    const {
      currentTarget: {
        dataset: {
          value: { value },
        },
      },
    } = e;
    this.setData({
      tabsActived: value,
    });
    this.resetPage();
    this.getList(true).then(() => {
      wx.hideLoading();
    });
  },
  //----搜索框start---
  inputFocus() {
    this.setData({ isInputFocus: true });
  },
  inputBlur() {
    this.setData({ isInputFocus: false });
    // this.queryNearbyShopListReq();
  },
  bindKeyInput: function (e) {
    this.setData({
      params: {
        ...this.data.params,
        name: e.detail.value,
      },
    });
    debounce(() => {
      this.resetPage();
      this.getList(true);
    }, 500)();
  },
  //----搜索框end---
  //列表组件滑动s
  nextPage() {
    if (!this.data.hasNextPage) return;
    const pageNum = this.data.params.pageNum + 1;
    this.setData({
      params: {
        ...this.data.params,
        pageNum,
      },
    });
    this.getList(false);
  },
  onChangeShowShopInfo(e) {
    const { detail } = e;
    if (detail.isToTop === null || detail.isToTop === undefined) return;
    this.setData({
      // isShowShopInfo: detail,
      isScrollToTop: detail.isToTop,
    });
  },
});
